﻿using System;
using System.IO;

namespace HAOest.IO
{
    /// <summary>
    /// 文件备份类
    /// <para>作者：邓斌</para>
    /// <para>修订：2012-09-28 V1.0</para>
    /// </summary>
    public class FileBackup
    {
        /// <summary>
        /// 简单备份
        /// </summary>
        /// <param name="filePath">文件地址</param>
        /// <param name="overwrite">是否允许覆盖已存在的备份文件</param>
        public static void SimpleBackup(String filePath, Boolean overwrite)
        {
            File.Copy(filePath, filePath + ".bak", overwrite);
        }

        /// <summary>
        /// 带时间的备份
        /// <para>备份文件的文件名以“.当前时间.bak”结尾</para>
        /// </summary>
        /// <param name="filePath">文件地址</param>
        public static void BackupWithTime(String filePath)
        {
            File.Copy(filePath, filePath + "." + DateTime.Now.ToString("yyMMddHHmmss") + ".bak", true);
        }

        /// <summary>
        /// 多重备份
        /// <para>允许多个备份共存，文件名以“.当前时间.bak”结尾</para>
        /// </summary>
        /// <param name="filePath">需要备份的文件Path</param>
        /// <param name="maxBackupNum">最多允许的备份数目</param>
        public static void MultipleBackup(String filePath, int maxBackupNum)
        {
            DirectoryInfo directoryInfo = new DirectoryInfo(filePath);//获取文件目录信息
            BackupWithTime(filePath);//备份文件
            FileInfo[] fileInfo = directoryInfo.Parent.GetFiles(Path.GetFileName(filePath) + ".*.bak");//获取目录下所有备份文件
            while (fileInfo.Length > maxBackupNum)//如果数目超过限制则删除最前面的
            {
                //【此处要不要先排序？怎么排序？】
                fileInfo[0].Delete();
                fileInfo = directoryInfo.Parent.GetFiles(Path.GetFileName(filePath) + ".*.bak");
            }
        }

    }
}
